import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { Permission } from '../database/models';
import { utils } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 创建权限
 */
export async function createPermission(ctx: Context): Promise<void> {
  const { name, code, description } = ctx.request.body as {
    name?: string;
    code?: string;
    description?: string;
  };

  if (!name || !code) {
    error(ctx, ResponseCode.BAD_REQUEST, '权限名称和代码不能为空');
    return;
  }

  // 保护默认系统管理员权限代码
  if (code === 'SYSTEM_ADMIN') {
    error(ctx, ResponseCode.FORBIDDEN, 'SYSTEM_ADMIN 权限代码已被系统保留，不可使用');
    return;
  }

  // 检查权限代码是否已存在
  const existing = await queryOne<Permission>('SELECT * FROM permissions WHERE code = ?', [code]);
  if (existing) {
    error(ctx, ResponseCode.CONFLICT, '权限代码已存在');
    return;
  }

  const id = utils.generateUUID();
  await query(
    'INSERT INTO permissions (id, name, code, description) VALUES (?, ?, ?, ?)',
    [id, name, code, description || null]
  );

  const newPermission = await queryOne<Permission>('SELECT * FROM permissions WHERE id = ?', [id]);
  success(ctx, newPermission);
}

/**
 * 更新权限
 */
export async function updatePermission(ctx: Context): Promise<void> {
  const { id, name, code, description } = ctx.request.body as {
    id?: string;
    name?: string;
    code?: string;
    description?: string;
  };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '权限ID不能为空');
    return;
  }

  const permission = await queryOne<Permission>('SELECT * FROM permissions WHERE id = ?', [id]);
  if (!permission) {
    error(ctx, ResponseCode.NOT_FOUND, '权限不存在');
    return;
  }

  // 保护默认系统管理员权限：不允许修改 code
  if (permission.code === 'SYSTEM_ADMIN' && code !== undefined && code !== 'SYSTEM_ADMIN') {
    error(ctx, ResponseCode.FORBIDDEN, '系统管理员权限的代码不可修改');
    return;
  }

  const updates: string[] = [];
  const params: any[] = [];

  if (name !== undefined) {
    updates.push('name = ?');
    params.push(name);
  }
  if (code !== undefined) {
    // 再次检查，防止修改系统管理员权限的 code
    if (permission.code === 'SYSTEM_ADMIN' && code !== 'SYSTEM_ADMIN') {
      error(ctx, ResponseCode.FORBIDDEN, '系统管理员权限的代码不可修改');
      return;
    }
    // 检查新代码是否已被其他权限使用
    const existing = await queryOne<Permission>('SELECT * FROM permissions WHERE code = ? AND id != ?', [code, id]);
    if (existing) {
      error(ctx, ResponseCode.CONFLICT, '权限代码已存在');
      return;
    }
    updates.push('code = ?');
    params.push(code);
  }
  if (description !== undefined) {
    updates.push('description = ?');
    params.push(description);
  }

  if (updates.length > 0) {
    params.push(id);
    await query(`UPDATE permissions SET ${updates.join(', ')} WHERE id = ?`, params);
  }

  const updatedPermission = await queryOne<Permission>('SELECT * FROM permissions WHERE id = ?', [id]);
  success(ctx, updatedPermission);
}

/**
 * 删除权限
 */
export async function deletePermission(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '权限ID不能为空');
    return;
  }

  const permission = await queryOne<Permission>('SELECT * FROM permissions WHERE id = ?', [id]);
  if (!permission) {
    error(ctx, ResponseCode.NOT_FOUND, '权限不存在');
    return;
  }

  // 保护默认系统管理员权限，不允许删除
  if (permission.code === 'SYSTEM_ADMIN') {
    error(ctx, ResponseCode.FORBIDDEN, '系统管理员权限不可删除');
    return;
  }

  // 删除权限关系
  await query('DELETE FROM user_permissions WHERE permission_id = ?', [id]);
  
  // 删除权限
  await query('DELETE FROM permissions WHERE id = ?', [id]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询权限列表
 */
export async function getPermissionList(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 10, name, code } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    name?: string;
    code?: string;
  };

  let sql = 'SELECT * FROM permissions WHERE 1=1';
  const params: any[] = [];

  if (name) {
    sql += ' AND name LIKE ?';
    params.push(`%${name}%`);
  }
  if (code) {
    sql += ' AND code LIKE ?';
    params.push(`%${code}%`);
  }

  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const permissions = await query<Permission>(sql, params);
  const totalResult = await queryOne<{ count: number }>(
    'SELECT COUNT(*) as count FROM permissions WHERE 1=1' + 
    (name ? ' AND name LIKE ?' : '') + 
    (code ? ' AND code LIKE ?' : ''),
    params.slice(0, -2)
  );

  success(ctx, {
    list: permissions,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 查询权限详情
 */
export async function getPermissionDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '权限ID不能为空');
    return;
  }

  const permission = await queryOne<Permission>('SELECT * FROM permissions WHERE id = ?', [id]);
  if (!permission) {
    error(ctx, ResponseCode.NOT_FOUND, '权限不存在');
    return;
  }

  success(ctx, permission);
}

